<template>
  <el-dialog class='addApp-modal' v-model="visible" :title="data.title" @close="close" :width="650">
    <el-form :label-width="120" :model="data.form" ref="formRef" :rules="data.formRules">
      <el-form-item label="应用ID" prop="clientId">
        <el-input v-model="data.form.clientId" :disabled='!!defaultData' />
      </el-form-item>
      <el-form-item label="应用名" prop="clientName">
        <el-input v-model="data.form.clientName" />
      </el-form-item>
      <el-form-item label="密钥" prop="clientSecret" v-if='!!defaultData'>
        <span>{{data.form.clientSecret}}</span>
      </el-form-item>
      <el-form-item label="授权模式" prop="authorizedGrantTypes">
        <el-select v-model="data.form.authorizedGrantTypes" placeholder="请输选择支持的模式" clearable multiple class="w-full">
          <el-option v-for="item in authorizedTypes" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="回调地址" prop="webServerRedirectUri">
        <el-input v-model="data.form.webServerRedirectUri" />
      </el-form-item>
      <el-form-item label="令牌时效(s)" prop="accessTokenValidity">
        <el-input-number v-model="data.form.accessTokenValidity" controls-position="right" class='w-full'/>
      </el-form-item>
      <el-form-item label="刷新时效(s)" prop="refreshTokenValidity">
        <el-input-number type="number" v-model="data.form.refreshTokenValidity" controls-position="right" class='w-full'/>
      </el-form-item>
      <el-form-item label="组织类型" prop="syncSF">
        <el-radio-group v-model="data.form.syncSF" :disabled='!!defaultData'>
          <el-radio :label="0">自建部门组织</el-radio>
          <el-radio :label="1">同步SF组织</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="flex justify-end">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="data.submitEvent" :loading="state.loading">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, toRefs, watch, ref, nextTick } from 'vue';
import { addApp, updateApp } from '/@/api/app';
import { useMessage } from '/@/hooks/web/useMessage';
import { AUTH_TYPE_LIST } from './const.js'
import { clientIdValidator } from '/@/utils/formRules'

const { createMessage } = useMessage();

const state = reactive({
  loading: false
})

const props = defineProps({
  data: {
    type: Object || undefined,
    default: () => undefined
  },
  visible: {
    type: Boolean,
    default: false,
  }
});

const emit = defineEmits(['success', 'update:visible'])

const validate = async (_rule, value) => {
  if (!Number.isInteger(value)) {
    return Promise.reject('请输入整数');
  } else if (value < 0) {
    return Promise.reject('请输入非负整数');
  } else {
    return Promise.resolve();
  }
}
const data = reactive({
  title: '新建应用',
  updateMode: false,
  form: {
    id: undefined,
    clientId: '',
    clientName: '',
    clientSecret: '',
    // scope: '',
    authorizedGrantTypes: [],
    webServerRedirectUri: '',
    accessTokenValidity: 0,
    refreshTokenValidity: 0,
    additionalInformation: '',
    syncSF: 0,
  },
  formRules: {
    clientId: [{ required: true, message: '请输入应用id', trigger: 'blur' }, { validator: clientIdValidator, trigger: 'blur'}],
    clientName: [{ required: true, message: '请输入应用名', trigger: 'blur' }],
    authorizedGrantTypes: [{ required: true, message: '请输选择授权模式', trigger: 'blur', type: 'array' }],
    webServerRedirectUri: [{ required: true, message: '请输入回调地址', trigger: 'blur' }],
    accessTokenValidity: [
      { required: true, message: '请输入令牌时效', trigger: 'blur', type: 'number' },
      { validator: validate, trigger: 'blur' },
    ],
    refreshTokenValidity: [
      { required: true, message: '请输入刷新时效', trigger: 'blur', type: 'number' },
      { validator: validate, trigger: 'blur' },
    ],
  },
  treeData: [],
  submitEvent: () => null as any,
});

const { data: defaultData, visible } = toRefs(props);

const authorizedTypes = ref(AUTH_TYPE_LIST)

const updateAction = async () => {
  formRef.value.validate(async v => {
    if(v) {
      let params = {
        id: data.form.id,
        clientId: data.form.clientId,
        clientName: data.form.clientName,
        authorizedGrantTypes: data.form.authorizedGrantTypes.join(','),
        webServerRedirectUri: data.form.webServerRedirectUri,
        accessTokenValidity: data.form.accessTokenValidity,
        refreshTokenValidity: data.form.refreshTokenValidity,
        additionalInformation: data.form.additionalInformation,
      };
      state.loading = true;
      let { respCode, respMsg } = await updateApp(params);
      state.loading = false;
      createMessage({
            message: respMsg,
          });
      if (respCode == 200) {
        emit('update:visible', false);
        emit('success', { id: data.form.id, clientName: data.form.clientName, autoFlag: data.form.syncSF, type: 'update' })
      }
    }
  })
};
const createAction = async () => {
  formRef.value.validate(async v => {
    if(v) {
      let params = {
        id: undefined,
        clientId: data.form.clientId,
        clientName: data.form.clientName,
        authorizedGrantTypes: data.form.authorizedGrantTypes.join(','),
        webServerRedirectUri: data.form.webServerRedirectUri,
        accessTokenValidity: data.form.accessTokenValidity,
        refreshTokenValidity: data.form.refreshTokenValidity,
        additionalInformation: data.form.additionalInformation,
        autoFlag: data.form.syncSF,
      };
      state.loading = true;
      let { data: resp_data, respCode, respMsg } = await addApp(params);
      state.loading = false;
      if (respCode == 200) {
        createMessage({
            message: respMsg,
          });
        emit('update:visible', false);
        emit('success', { id: resp_data.id, clientName: data.form.clientName, autoFlag: data.form.syncSF, type: 'add' })
      }
    }
  })
};
data.submitEvent = createAction;

const formRef = ref();
watch(visible, (nv: any) => {
  if (nv) {
    data.updateMode = props.data?.id ? true : false;
    data.title = data.updateMode ? '编辑应用' : '新建应用';
    data.submitEvent = data.updateMode ? updateAction : createAction;
    if (data.updateMode) {
      nextTick(() => {
        data.form.id = defaultData?.value?.id || undefined;
        data.form.clientId = defaultData?.value?.clientId;
        data.form.clientName = defaultData?.value?.clientName;
        data.form.clientSecret = defaultData?.value?.clientSecretStr;
        data.form.authorizedGrantTypes = defaultData?.value?.authorizedGrantTypes.split(',') || [];
        data.form.webServerRedirectUri = defaultData?.value?.webServerRedirectUri;
        data.form.accessTokenValidity = defaultData?.value?.accessTokenValidity;
        data.form.refreshTokenValidity = defaultData?.value?.refreshTokenValidity;
        data.form.additionalInformation = defaultData?.value?.additionalInformation;
        data.form.syncSF = defaultData?.value?.autoFlag;
      })
    } 
  }
})

const close = () => {
  formRef.value.resetFields();
  emit('update:visible', false)
}
</script>
